package com.project.zsxd.server.login.controller;

import com.alibaba.fastjson.JSONObject;
import com.project.zsxd.server.annotation.LoginPass;
import com.project.zsxd.server.common.bean.Result;
import com.project.zsxd.server.common.enums.ResultEnum;
import com.project.zsxd.server.common.helper.ThirdPartyLoginHelper;
import com.project.zsxd.server.common.util.CommonUtil;
import com.project.zsxd.server.common.util.JWTUtil;
import com.project.zsxd.server.common.util.LogUtil;
import com.project.zsxd.server.user.entity.User;
import com.project.zsxd.server.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/thirdPartyLogin")
public class ThirdPartyLoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ThirdPartyLoginHelper thirdPartyLoginHelper;

    /**
     * 微信登录回调
     * @param request
     * @return
     */
    @RequestMapping("/callback/wx")
    @LoginPass
    public Result wxCallback(@RequestBody JSONObject paramObj,
            HttpServletRequest request, HttpServletResponse response){
        String host = request.getHeader("host");
        String code = paramObj.getString("code");
        JSONObject userInfoObj = paramObj.getJSONObject("userInfo");
        Result result = new Result();
        if (!CommonUtil.isEmpty(code)) {// 如果不为空
            try {
                // 获取token和openid
                Map<String, String> map = thirdPartyLoginHelper.getWxTokenAndOpenid(code, host);
//                Map<String, String> map = new HashMap<>();
//                map.put("openId", "123456789");
                String openId = map.get("openId");
                userInfoObj.put("openId", openId);
//                LogUtil.info("openId:{}",openId);
                if (!CommonUtil.isEmpty(openId)) {// 如果openID存在
                    Map<String, Object> dataMap = new HashMap<>();
                    // 根据openid查询用户是否存在
                    User queryUser = userService.queryByOpenId(openId);
                    if (queryUser == null) {
                        queryUser = ThirdPartyLoginHelper.getWxUserinfo(userInfoObj);
                        queryUser = userService.registerOpenUser(queryUser);
                    } else {
                        ThirdPartyLoginHelper.updateWxUserinfo(queryUser, userInfoObj);
                        userService.updateById(queryUser);
                    }
                    List<String> roles = userService.queryRolesByUserName(queryUser.getUserName());
                    List<String> permissions = userService.queryPermissionsByUserName(queryUser.getUserName());

                    dataMap.put("userInfo", queryUser);
                    dataMap.put("token", JWTUtil.sign(queryUser.getUserName(), queryUser.getPasswd()));
                    dataMap.put("roles", roles);
                    dataMap.put("permissions", permissions);
                    result.setData(dataMap);
                } else {// 如果未获取到OpenID
                    LogUtil.error("OpenId不存在。host:{},code:{}", host, code);
                    result.setResultEnum(ResultEnum.USER_AUTHENTICATION_ERROR);
                }
            } catch (Exception e) {
                LogUtil.error("host:{},code:{},error:{}", host, code, e.getMessage());
                result.setResultEnum(ResultEnum.USER_AUTHENTICATION_ERROR);
            }
        } else {// 如果没有返回令牌，则直接返回到登录页面
            LogUtil.error("Code不存在。host:{},code:{}", host, code);
            result.setResultEnum(ResultEnum.USER_AUTHENTICATION_ERROR);
        }
        return result;
    }

}
